/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.backup;

import com.wtkj.vo.dzzf.base.kfwd.OBU;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.dao.backup.BackupInfosDao;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.*;

/**
 * 备份obu信息服务实现
 * @author MaShibo
 * @date 2017/12/27.
 */
@Service
public class BackupObuIdInfoService {

	private static final Logger LOGGER = LoggerFactory.getLogger(BackupObuIdInfoService.class);

	@Resource
	private ThreadPoolTaskExecutor executor;

	@Resource
	private BaseInfoService baseInfoService;

	@Resource
	private BackupInfosDao backupInfosDao;

	@Resource
	private TransferUserInfoDao transferUserInfoDao;

	private void process(){
		int total = backupInfosDao.queryObuIdsNum();
		LOGGER.info("共{}条数据待处理", total);
		int corePoolSize = executor.getCorePoolSize();
		int maxPerSize = DEFAULT_PROCESS_NUM * corePoolSize;
		int count;
		int processNum;
		if (total < maxPerSize){
			count = corePoolSize;
			processNum = (int) Math.ceil((double)total/count);
		}else {
			count = (int) Math.ceil((double)total/DEFAULT_PROCESS_NUM);
			processNum = DEFAULT_PROCESS_NUM;
		}
		List<Future<Void>> futures = new ArrayList<>(count);
		for (int i = 0 ; i < count; i++){
			int num = i + 1;
			int startRow = (num - 1) * processNum + 1;
			int endRow = num * processNum > total ? total : num * processNum;
			futures.add(executor.submit(() -> {
				processOne(startRow, endRow);
				return null;
			}));
		}
		baseInfoService.getFutureResult(futures);
		executor.shutdown();
		System.exit(0);
	}

	/**
	 * 单次处理
	 * @param startRow 起始行号
	 * @param endRow 终止行号
	 */
	private void processOne(int startRow, int endRow){
		LOGGER.info("开始处理第{}行至第{}行数据", startRow, endRow);
		List<OBU> obus = backupInfosDao.queryObuInfosByRow(startRow, endRow);
		obus.forEach(obu -> {
			try {
				transferUserInfoDao.createTestObjcet(obu);
			} catch (Exception e) {
				LOGGER.error(e.getMessage(), e);
			}
		});
		LOGGER.info("第{}行至第{}行数据处理完毕", startRow, endRow);
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		BackupObuIdInfoService service = context.getBean(BackupObuIdInfoService.class);
		service.process();
	}
}
